﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace SharpSoft.Web
{
    public class APIExceptionFilter : IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            if (context.HttpContext.WebSockets.IsWebSocketRequest)
            {
                return;
            }
            if (context.ActionDescriptor is Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor cad)
            {
                if (cad.MethodInfo.ReturnType == typeof(ApiResult) || cad.MethodInfo.ReturnType == typeof(Task<ApiResult>))
                {//API接口直接反馈错误信息 
                    context.Result = new JsonResult(new ApiResult(-500,context.Exception.Message)); 
                }
            }

            //var req = context.HttpContext.Request;

            //if (req.Headers.ContainsKey("X-Requested-With") && req.Headers["X-Requested-With"] == "XMLHttpRequest")
            //{
            //    context.Result = new ContentResult() { StatusCode = 500, Content = context.Exception.Message };
            //}
            //else
            //{
            //    context.Result = new StatusCodeResult(500);
            //}
        }
    }
}
